/// Author: Samle
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'dart:convert' as convert;
import '../../../routes/app_pages.dart'; /// lib/app/routes/app_pages.dart
import '../../../../db/db_helper.dart';
import '../../../../store/page_store.dart';

class EditHelpTextController extends GetxController with StateMixin<List> {
  RxList helpTextList = [].obs;
  RxMap wordForm = {}.obs;
  TextEditingController val = TextEditingController();
  TextEditingController desc = TextEditingController();
  TextEditingController oldVal = TextEditingController();
  TextEditingController oldDesc = TextEditingController();
  GlobalKey<FormState> helpTextKey = GlobalKey<FormState>();
  TextEditingController search = TextEditingController();

  /// 查询参数集
  Map paramsForm = {
    "search": null,
    "id": null,
  };

  getHelpText() async {
    if (wordForm.value["helpText"] != null && wordForm.value["helpText"] != '' && wordForm.value["helpText"] != 'null'){
      return json.decode(wordForm.value["helpText"]);
    } else {
      wordForm.value["helpText"] = json.encode({
        'default': {"val": "","desc": ""},
        'self': []
      });
      return {
        'default': {"val": "","desc": ""},
        'self': []
      };
    }
  }
  /// 获取 HelpText 数据集
  getHelpTextList() async {
    // wordForm.value = Get.arguments;
    wordForm.value = await localData.getWordsById(Get.arguments['id']);
    if (wordForm.value.isNotEmpty && wordForm.value != null && wordForm.value.containsKey('helpText')){
      Map helpText = await getHelpText();
      if (helpText.containsKey('self')){
        // helpTextList.value = helpText['self'];
        helpTextList.value = helpText['self'].where((element) => (element.containsKey('val') && element['val'].contains(search.text))).toList();
        change(helpTextList, status: RxStatus.success());
      } else {
        wordForm.value['helpText']['self'] = [];
        helpTextList.value = [];
        change(helpTextList, status: RxStatus.success());
      }
    }
  }
  reStr(String oldStr){
    String newStr = oldStr.replaceAll("'", "''");
    return newStr;
  }
  updateWord() async {
    var newWord = json.decode(json.encode(wordForm.value));
    newWord['belong'] = reStr(newWord['belong']);
    newWord['name'] = reStr(newWord['name']);
    newWord['ukphone'] = reStr(newWord['ukphone']);
    newWord['usphone'] = reStr(newWord['usphone']);
    newWord['trans'] = reStr(newWord['trans']);
    newWord['syno'] = reStr(newWord['syno']);
    newWord['relWord'] = reStr(newWord['relWord']);
    newWord['sentence'] = reStr(newWord['sentence']);
    newWord['phrase'] = reStr(newWord['phrase']);
    newWord['exam'] = reStr(newWord['exam']);
    newWord['helpText'] = reStr(newWord['helpText']);
    newWord['soundText'] = reStr(newWord['soundText']);
    print(newWord);
    var updateRes = await localData.updateWords(newWord);
  }

  /// 数据表单
  Map dataForm = {
    "id": null,
    "val": null,
    "desc": null,
  };

  /// 跳转编辑界面 按需要修改路由
  toEditPage() {
    Get.toNamed('/edit-helpText', arguments: dataForm)?.then((value) async {
      if (value == null) {
        return;
      } else {
        if (value.containsKey("id") && value['id'] != null &&
            value['id'] != '') {
          dataForm = value;
          updateHelpText();
        } else {
          dataForm = value;
          addHelpText();
        }
      }
    });
  }

  /// 修改 HelpText 实例
  updateHelpText() async {
    try {
      // var result = await localData.updateHelpText(dataForm);
      Fluttertoast.showToast(
        msg: "更新成功！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        backgroundColor: Colors.green,
        textColor: Colors.white,
        fontSize: 16.0,
      );
      onInit();
    } catch (e) {
      /// 更新失败后回调
      Fluttertoast.showToast(
        msg: "更新失败！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0,
      );
    }
  }

  /// 新增 HelpText 实例
  addHelpText() async {
    try {
      // var result = await localData.addHelpText(dataForm);
      Fluttertoast.showToast(
        msg: "新增成功！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        backgroundColor: Colors.green,
        textColor: Colors.white,
        fontSize: 16.0,
      );
      onInit();
    } catch (e) {
      /// 新增失败后回调
      Fluttertoast.showToast(
        msg: "新增失败！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0,
      );
    }
  }

  /// 数据表单
  Map cleanDataForm = {
    "id": null,
    "val": null,
    "desc": null,
  };

  /// 删除 HelpText 实例
  delHelpText(form) async {
    if (form.containsKey("id") && form["id"] != "") {
      try {
        Fluttertoast.showToast(
          msg: "删除成功！",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          backgroundColor: Colors.green,
          textColor: Colors.white,
          fontSize: 16.0,
        );
        onInit();
      } catch (e) {
        /// 删除失败后回调
        Fluttertoast.showToast(
          msg: "删除失败！",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0,
        );
      }
    }
  }

  @override
  Future<void> onInit() async {
    await getHelpTextList();
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }
}
